import pulsar
import asyncio
import time
import json
from django.conf import settings

# 创建命名空间
# PUT http://api.yisbar.com:28080/admin/v2/namespaces/public/yisbar

namespace = "workReport"
prname = "yisbar_server" if settings.DEBUG else "yisbar_server_debug"


def has_Pulsar_Conf():
    """取配置文件"""
    try:
        with open(settings.CONF / "pulsar.json", "r") as fs:
            code = fs.read()
            dictcode = json.loads(code)
    except BaseException as err:
        dictcode = None
    return dictcode


async def send_alert_queue(host, message):
    """pulsar 生产者"""
    conf = has_Pulsar_Conf()
    if not conf or not conf.get("status"):
        return
    # print(conf)
    try:
        # non-persistent 非持久化;        # persistent 持久化
        client = pulsar.Client(f'pulsar://{conf.get("host")}:{conf.get("pport")}')
        producer = client.create_producer(
            f"non-persistent://public/{namespace}/{host}",
            producer_name=prname,
        )
        producer.send(f"{message}".encode("utf-8"))
        client.close()
    except BaseException as err:
        pass
    # print("发送消息队列完成...")


# await send_alert_queue()
# or
# asyncio.run(send_alert_queue())


def SendAsyncMessage(pid, message):
    """
    发送异步消息
    pid 消息主题
    message 消息内容结构体
    """
    asyncio.run(
        send_alert_queue(
            host=f"{pid}",
            message=message,
        )
    )
